﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tsanie.FlvTag {
    static class ByteExtension {

        public static int WriteString(this byte[] dest, int pos, string str, bool type) {
            if (string.IsNullOrEmpty(str))
                return 0;
            if (type)
                dest[pos++] = 0x2;
            byte[] bs = Encoding.ASCII.GetBytes(str);
            pos = dest.PutInt(pos, bs.Length, 2);
            bs.CopyTo(dest, pos);
            pos += bs.Length;
            return pos;
        }
        public static int WriteString(this byte[] dest, int pos, string str) {
            return dest.WriteString(pos, str, false);
        }

        public static int PutInt(this byte[] dest, int pos, int val, int length) {
            if (length <= 0)
                return pos;
            for (int i = length - 1; i >= 0; i--) {
                dest[pos + i] = (byte)(val & 0xFF);
                val >>= 8;
            }
            return pos + length;
        }

        public static int WriteByte(this byte[] dest, int pos, byte b) {
            dest[pos++] = 0x1;
            dest[pos++] = b;
            return pos;
        }

        public static int WriteDouble(this byte[] dest, int pos, double val) {
            dest[pos++] = 0;
            byte[] bd = BitConverter.GetBytes(val);
            for (int i = 0; i < 8; i++) {
                dest[pos++] = bd[7 - i];
            }
            return pos;
        }

        public static int WriteArray(this byte[] dest, int pos, List<double> ds, double offset) {
            dest[pos++] = 0xa;
            pos = PutInt(dest, pos, ds.Count, 4);
            for (int i = 0; i < ds.Count; i++) {
                pos = WriteDouble(dest, pos, ds[i] + offset);
            }
            return pos;
        }
        public static int WriteArray(this byte[] dest, int pos, List<double> ds) {
            return WriteArray(dest, pos, ds, 0.0);
        }

        public static void PutTime(this byte[] bs, int pos, uint value) {
            for (int i = 2; i >= 0; i--) {
                bs[pos + i] = (byte)(value & 0xff);
                value >>= 8;
            }
            bs[pos + 3] = (byte)(value & 0xff);
        }

    }
}
